﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using Web.SystemConfig.Services;
using System.Data;
using Microsoft.Practices.Unity;
using ePlanet.ArchiveMange.Services;
using ePlanet.ArchiveMange.Models;
using DreamBuilder.Core.Message;
using DreamBuilder.Core.Container;
using Web.SystemConfig.WorkFlow;
using Web.SystemConfig.SysCache;
using System.Text;
using CommonModule;
using ePlanet.ArchiveMange.DataAccess;

namespace Web.Views.ArchiveHistory
{
    public partial class ArchiveVolHistoryEdit : PageBase
    {
        #region
        protected string archiveTypeName=string.Empty;
        //如果编目为空或者是错误的值，则默认显示这个类别
        string catalog = string.Empty;
        #endregion
        #region 页面属性
        [Dependency]
        public ICodeTable CodeTableService
        {
            get;
            set;
        }


        [Dependency]
        public IArchiveMenuService ArchiveMenuService
        {
            get;
            set;
        }

        /// <summary>
        /// 档案ID
        /// </summary>
        public string ArchiveID
        {
            get
            {
                if (Request.QueryString["archiveId"] != null)
                {
                    return Request.QueryString["archiveId"];
                }
                else
                {
                    throw new Exception("档案ID不能为空");
                }
            }
        }


        /// <summary>
        /// 历史档案类型ID
        /// </summary>
        public int ArchiveHistoryType
        {
            get
            {
                if (Request.QueryString["archivehistoryType"] != null)
                {
                    return int.Parse(Request.QueryString["archivehistoryType"]);
                }
                else
                {
                    throw new Exception("历史档案类型ID不能为空");
                }
            }
        }

        [Dependency]
        public IDocumentArchiveVolService DocumentVolService
        {
            get;
            set;
        }

        [Dependency]
        public IDocumentArchiveVolFileService DocumentVolFileService
        {
            get;
            set;
        }

        [Dependency]
        public IZongheVolService ZongheVolService
        {
            get;
            set;
        }

        [Dependency]
        public IZongheVolFileService ZongheVolFileService
        {
            get;
            set;
        }
        #endregion

        #region 页面初始化
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    DataHelper helper = new DataHelper();
                    //初始化附件数据连接字符串
                    this.attachArchive.AttachmentDBHelperString = helper.GetDbHelperNameByArchiveType(ArchiveHistoryType.ToString());
                    this.attachArchive.ObjectID = ArchiveID;
                    this.attachArchive.ObjectTableName = "";
                    AddAttachmentInfos();
                    InitControls();
                    LoadData();

                }
                catch(Exception ex)
                {
                    WriteErrorLog(ex.StackTrace);
                    Alert(ex.Message);
                }
            }
        }
        #endregion

        #region 按钮事件
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddArchiveBack_Click(object sender, EventArgs e)
        {
            bool bReturn = SaveData();
            LoadData();
            if (bReturn)
            {
                Alert("文书档案修改成功!");
            }
            else
            {
                Alert("修改出错，请检查输入重新尝试!");
            }
        }

        /// <summary>
        /// 返回按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBack_Click(object sender, EventArgs e)
        {
           // this.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "window.close();", true);
        }

        #endregion

        #region 页面方法
        /// <summary>
        /// 初始化数据项
        /// </summary>
        private void InitControls()
        {
            //初始化附件上传控件
            this.attachArchive.ObjectID = ArchiveID;


            //保管期限
            DataSet KeepTime = CodeTableService.GetCodeTableDataByType("KeepTime");
            if (KeepTime != null && KeepTime.Tables.Count > 0)
            {
                this.ddlKeepTime.DataSource = KeepTime;
                this.ddlKeepTime.DataTextField = "Code_Desc";
                this.ddlKeepTime.DataValueField = "CodeTableID";
                this.ddlKeepTime.DataBind();
                this.ddlKeepTime.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            DataSet CarrierType = CodeTableService.GetCodeTableDataByType("CarrierType");
            if (CarrierType != null && CarrierType.Tables.Count > 0)
            {
                this.ddlCarrierType.DataSource = CarrierType;
                this.ddlCarrierType.DataTextField = "Code_Desc";
                this.ddlCarrierType.DataValueField = "CodeTableID";
                this.ddlCarrierType.DataBind();
                this.ddlCarrierType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            DataSet SecurityData = CodeTableService.GetCodeTableDataByType("SecurityType");
            if (CarrierType != null && CarrierType.Tables.Count > 0)
            {
                this.ddlSecurity.DataSource = SecurityData;
                this.ddlSecurity.DataTextField = "Code_Desc";
                this.ddlSecurity.DataValueField = "CodeTableID";
                this.ddlSecurity.DataBind();
                this.ddlSecurity.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            this.txtArchiveType.Enabled = false;
            if (Request.QueryString["readonly"] != null)
            {
                this.btnAddArchiveBack.Visible = false;
            }

            switch (ArchiveHistoryType)
            {
                //文书卷101

                case ((int)ArchiveHistoryTypeEnum.DocumentVol):
                    archiveTypeName = "文书卷";
                    catalog = "W";
                    break;
                //文书卷内件102
                case ((int)ArchiveHistoryTypeEnum.DocumentVolFile):
                    archiveTypeName = "文书卷内件";
                    catalog = "W";
                    break;
                //勘探综合卷
                case ((int)ArchiveHistoryTypeEnum.ZongheVol):
                    archiveTypeName = "勘探综合卷";
                    catalog = "K01";
                    break;
                //勘探综合卷内件
                case ((int)ArchiveHistoryTypeEnum.ZongheVolFile):
                    archiveTypeName = "勘探综合件";
                    catalog = "K01";
                    break;
            }
            
            //this.h_ArchiveTypeId.Value = ReqArchiveType;
            //如果是修改，保存并录入不显示
            //if (Request.QueryString["archiveId"] != null)
            //{
            //    this.btnAddArchive.Visible = false;
            //}
        }

        /// <summary>
        /// 加载页面数据
        /// </summary>
        private void LoadData()
        {
            DataTable dt = GetArchiveData();
            if (dt.Rows.Count > 0)
            {
                this.CurrentPageState = PageState.State_Edit;

                DataRow row = dt.Rows[0];
                this.h_archiveTypeId.Value = row["ARCHIVETYPE"].ToString();
                ArchiveMangeModal.ARCHIVEMENUDataTable dtMenu = ArchiveMenuService.GetArchiveMenuById(row["ARCHIVETYPE"].ToString());
                if (dtMenu.Rows.Count > 0)
                {
                    ArchiveMangeModal.ARCHIVEMENURow drMenu = dtMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow;
                    this.txtArchiveType.Text = drMenu.ARCHIVEMENU;
                }
                else
                {
                    //如果类别号读出错误，则显示默认的类别号
                    this.txtArchiveType.Text = catalog;
                }
                this.txtArchiveNum.Text =row["ARCHIVENUM"].ToString();
                this.txtAwardType.Text =row["AWARDTYPE"].ToString();
                this.txtCopies.Text = row["COPIES"].ToString();
                this.txtRecordUser.Text =row["RECORDUSER"].ToString();
                if (row["EndTime"] != DBNull.Value)
                {
                    this.txtEndTime.Text = Convert.ToDateTime(row["EndTime"]).FormatToDate();
                }
                else
                {
                    this.txtEndTime.Text = string.Empty;
                }
                this.txtDocumentNum.Text =row["DOCUMENTNUM"].ToString();
                this.txtFileOrg.Text =row["FileOrgID"].ToString();
                if (row["FileTime"] != DBNull.Value)
                {
                    this.txtFileTime.Text = Convert.ToDateTime(row["FileTime"]).FormatToDate();
                }
                else
                {
                    this.txtFileTime.Text = string.Empty;
                }
                this.txtFileUser.Text = row["FileUser"].ToString();
                this.txtPageCou.Text = row["PegeCou"].ToString();
                if (row["RecordTime"] != DBNull.Value)
                {
                    this.txtRecordTime.Text = Convert.ToDateTime(row["RecordTime"]).FormatToDate();
                }
                else
                {
                    this.txtRecordTime.Text = string.Empty;
                }
                this.txtRecordUser.Text = row["RecordUser"].ToString();
                this.txtRemark.Text = row["Remark"].ToString();
                this.txtResponsibleUser.Text = row["RESPONSIBLEUSER"].ToString();
                if (row["StartTime"] != DBNull.Value)
                {
                    this.txtStartTime.Text = Convert.ToDateTime(row["StartTime"]).FormatToDate();
                }
                else
                {
                    this.txtStartTime.Text = string.Empty;
                }
                this.txtSummary.Text = row["Summary"].ToString();
                this.txtTitle.Text = row["Title"].ToString();
                this.txtTiyao.Text = row["Tiyao"].ToString();
                this.ddlCarrierType.SelectedValue = row["F_CARRIERTYPE"].ToString();
                this.ddlKeepTime.SelectedValue = row["F_KEEPTIME"].ToString();
                this.ddlSecurity.SelectedValue = row["F_SECURITYTYPE"].ToString();
            }
        }

        /// <summary>
        /// 根据页面参数获取页面数据（弱类型DataTable）
        /// </summary>
        /// <returns></returns>
        private DataTable GetArchiveData()
        {
            //根据参数类型加载数据
            DataTable dtArchiveHistory = null;
            switch (ArchiveHistoryType)
            {
                //文书卷101
                    
                case ((int)ArchiveHistoryTypeEnum.DocumentVol):
                    dtArchiveHistory = DocumentVolService.GetAllDocumenArchivetDataById(ArchiveID);
                    break;
                //文书卷内件102
                case ((int)ArchiveHistoryTypeEnum.DocumentVolFile):
                    dtArchiveHistory = DocumentVolFileService.GetAllDocumenArchivetDataById(ArchiveID);
                    break;
                //勘探综合卷
                case ((int)ArchiveHistoryTypeEnum.ZongheVol):
                    dtArchiveHistory = ZongheVolService.GetAllZongheVolDataById(ArchiveID);
                    break;
                //勘探综合卷内件
                case ((int)ArchiveHistoryTypeEnum.ZongheVolFile):
                    dtArchiveHistory = ZongheVolFileService.GetAllZongheVolFileDataById(ArchiveID);
                    break;
            }
            return dtArchiveHistory;
        }

        /// <summary>
        /// 附件实体增加更多信息
        /// </summary>
        private void AddAttachmentInfos()
        {
            Hashtable addInfos = new Hashtable();
            addInfos.Add("FunctionID", "0"); //功能ID(1：发文文档 2：发文附件 3：收文文档 4：收文附件 5：即时消息附件 6：新闻附件)
            addInfos.Add("FileTypeID", ""); //附件文件夹类型
            addInfos.Add("FileURL", ""); //附件存储路径
            addInfos.Add("IsXml", "0"); //是否XML代码化
            addInfos.Add("CreateUserID", this.CurrentUser.User_ID); //用户ID 目前可以写个固定的值作为测试
            addInfos.Add("Remark", "档案附件"); //备注
            if (Session["AddInfos"] == null)
            {
                Session.Add("AddInfos", addInfos);
            }
            else
            {
                Session.Remove("AddInfos");
                Session.Add("AddInfos", addInfos);
            }
        }

        /// <summary>
        /// 验证页面数据
        /// </summary>
        /// <param name="errmsg">返回错误信息，验证正确错误信息为空</param>
        /// <returns>验证是否正确</returns>
        private bool VelidateData(out string errmsg)
        {
            //非空验证
            bool bReturn = true;
            StringBuilder msg = new StringBuilder();
            errmsg= string.Empty;
            string _lineChar = "\\n";
            if (string.IsNullOrEmpty(this.txtTitle.Text))
            {
                bReturn = false;
                msg.Append("题名不能为空!" + _lineChar);
            }
            //格式校验，日期
            if (!this.VelidateDate(this.txtStartTime.Text, out errmsg))
            {
                bReturn = false;
                msg.Append(errmsg + _lineChar);
            }
            if (!this.VelidateDate(this.txtEndTime.Text, out errmsg))
            {
                bReturn = false;
                msg.Append(errmsg + _lineChar);
            }
            if (!this.VelidateDate(this.txtFileTime.Text, out errmsg))
            {
                bReturn = false;
                msg.Append(errmsg + _lineChar);
            }
            if (!this.VelidateDate(this.txtRecordTime.Text, out errmsg))
            {
                bReturn = false;
                msg.Append(errmsg + _lineChar);
            }
            if (!this.VelidateInteger(this.txtPageCou.Text, out errmsg))
            {
                bReturn = false;
                msg.Append(errmsg + _lineChar);
            }
            if (!this.VelidateInteger(this.txtCopies.Text, out errmsg))
            {
                bReturn = false;
                msg.Append(errmsg + _lineChar);
            }
            errmsg = msg.ToString();
            return bReturn;
        }

        /// <summary>
        ///  保存页面数据
        /// </summary>
        /// <returns>是否保存成功</returns>
        private bool SaveData()
        {
            bool bReturn = true;
            //页面验证
            string errmsg = string.Empty;
            if (!VelidateData(out errmsg))
            {
                Alert(errmsg);
                bReturn = false;
            }
            else
            {
                DataSet ds = new DataSet();
                //数据保存
                DataTable dt = GetArchiveData();
                if (dt.Rows.Count > 0)
                {
                    DataRow row = dt.Rows[0];
                    row["ARCHIVENUM"] = this.txtArchiveNum.Text;
                    //row.ARCHIVETYPE = this.
                    row["AWARDTYPE"] = this.txtAwardType.Text;
                    decimal o_d = decimal.Zero;
                    decimal.TryParse(this.txtCopies.Text, out o_d);
                    row["COPIES"] = o_d;
                    //row.CREATETIME
                    //row.CREATEUSERID 
                    //row.DATAID
                    row["DOCUMENTNUM"] = this.txtDocumentNum.Text;
                    DateTime o_dt = DateTime.Now;
                    if (DateTime.TryParse(this.txtEndTime.Text, out o_dt))
                    {
                        row["ENDTIME"] = o_dt;
                    }
                    else
                    {
                        row["ENDTIME"] = DBNull.Value;
                    }
                    row["F_CARRIERTYPE"] = this.ddlCarrierType.SelectedValue;
                    //row.F_KEEPSECURITYTIME
                    row["F_KEEPTIME"] = this.ddlKeepTime.SelectedValue;
                    row["F_SECURITYTYPE"] = this.ddlSecurity.SelectedValue;
                    row["FILEORGID"] = this.txtFileOrg.Text;
                    if (DateTime.TryParse(this.txtFileTime.Text, out o_dt))
                    {
                        row["FILETIME"] = o_dt;
                    }
                    else
                    {
                        row["FILETIME"] = DBNull.Value;
                    }
                    row["FILEUSER"] = this.txtFileUser.Text;
                    //row.FULLFONDSNUM
                    row["LASTUPDATETIME"] = DateTime.Now;
                    row["LASTUPDATEUSER"] = this.CurrentUser.User_ID;
                    //row.MAINBODYNUM
                    decimal.TryParse(this.txtPageCou.Text,out o_d);
                    row["PEGECOU"] = o_d;
                    if (DateTime.TryParse(this.txtRecordTime.Text, out o_dt))
                    {
                        row["RECORDTIME"] = o_dt;
                    }
                    else
                    {
                        row["RECORDTIME"] = DBNull.Value;
                    }
                    row["RECORDUSER"] = this.txtRecordUser.Text;
                    row["REMARK"] = this.txtRemark.Text;
                    row["RESPONSIBLEUSER"] = this.txtResponsibleUser.Text;
                    if (DateTime.TryParse(this.txtStartTime.Text, out o_dt))
                    {
                        row["STARTTIME"] = o_dt;
                    }
                    else
                    {
                        row["STARTTIME"] = DBNull.Value;
                    }
                    //row.STATUSID
                    row["SUMMARY"] = this.txtSummary.Text;
                    row["TITLE"] = this.txtTitle.Text;
                    row["TIYAO"] = this.txtTiyao.Text;
                    ArchiveCommon dalCommon = new ArchiveCommon();
                    dt.TableName = dalCommon.GetArchiveDBTableName(ArchiveHistoryType.ToString());
                    dt.PrimaryKey = new DataColumn[] { dt.Columns["DataID"]};
                    dt.AcceptChanges();
                    row.SetModified();
                    ds.Tables.Add(dt);
                    dalCommon.InsertData(ds); ;
                }
               bReturn= bReturn && SaveAttachment();
            }
            return bReturn;
        }

        /// <summary>
        /// 保存附件
        /// </summary>
        /// <returns></returns>
        private bool SaveAttachment()
        {
            DataTable dt_Attach = this.attachArchive.GetSaveDataTable(this.attachArchive.ObjectID, this.attachArchive.ObjectTableName);
            return DocumentVolService.SaveAttach(dt_Attach, this.attachArchive.ObjectTableName, this.attachArchive.ObjectID,
                 this.attachArchive.AttachmentDBHelperString);
        }
        #endregion
    }
}
